package com.hl.sfzy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hl.sfzy.entity.Request;
import com.hl.sfzy.entity.User;
import com.hl.sfzy.mapper.UserMapper;
import com.hl.sfzy.service.UserService;
import com.hl.sfzy.utils.MD5Util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
//	添加
	@Override
	public int add(User user) {
		// 加密盐 用户账号+密码
		String  pass = user.getUserPassword() + user.getUserUserName();
		user.setUserPassword(pass);
		int add = userMapper.Insert(user);
		return add;
	}
// 修改
	@Override
	public int edit(User user) {
		int edit = userMapper.Update(user);
		return edit;
	}
//	根据id删除
	@Override
	public int remove(Integer userId) {
		int remove = userMapper.Delete(userId);
		return remove;
	}
//	批量删除
	@Override
	public int removeBatch(Integer[] userIds) {
			int removeBatch = userMapper.DeleteBatch(userIds);
		return removeBatch;
	}
//  查询所有
	@Override
	public List<User> find() {
		List<User> users = userMapper.Select();
		return users;
	}
//  分页查询
	@Override
	public PageInfo<User> findByPage(int pageNum, int pageSize, User user) {
		PageHelper.startPage(pageNum, pageSize);
		List<User> findByPage = userMapper.Select(user);
		PageInfo<User> pageInfo = new PageInfo<User>(findByPage);
		System.out.println(pageInfo);
		return pageInfo;
	}
//	根据Id查询
	@Override
	public User findById(Integer userId) {
		User user = userMapper.SelectById(userId);
		System.out.println(user);
		return user;
	}
//	登陆
	@Override
	public User login(String userUserName, String userPassword) {
		User user = userMapper.login(userUserName, userPassword);
		if(user!=null && user.getUserPassword().equalsIgnoreCase(MD5Util.encode(userUserName+userPassword))){
			return user;
		}else {
			return null;
		}
	}

	//	修改密码
	@Override
	public int updatePassword(Request request) {
		Long  passwordId = request.getPasswordId();
		String oldPassword = request.getOldPassword();
		String newPassword = request.getNewPassword();
		int code = 0;
		//查询用户
		User user = userMapper.SelectById(Math.toIntExact(passwordId));
		if (user!=null){
			if (user.getUserPassword().equalsIgnoreCase(MD5Util.encode(user.getUserUserName()+oldPassword))){
				user.setUserPassword(MD5Util.encode(user.getUserUserName()+newPassword));
				int i = userMapper.Update(user);
				if(i!=0){
					code = 1; //修改成功
				}else {
					code = -1; //修改失败
				}
			}else {
				code = -2;//旧密码错误
			}
 		}
		return code;
	}
}
